import { useState, useEffect } from 'react';

    /**
     * 自定义Hook，用于在localStorage中存储和检索数据
     * @param {string} key - localStorage键名
     * @param {any} initialValue - 初始值
     * @returns {Array} [storedValue, setValue, removeValue]
     */
    const useLocalStorage = (key, initialValue) => {
      // 获取初始值
      const [storedValue, setStoredValue] = useState(() => {
        try {
          const item = window.localStorage.getItem(key);
          // 如果localStorage中有值，则解析并返回
          return item ? JSON.parse(item) : initialValue;
        } catch (error) {
          console.error(`从localStorage获取键"${key}"时出错:`, error);
          return initialValue;
        }
      });

      // 更新localStorage和状态
      const setValue = (value) => {
        try {
          // 允许value是一个函数，类似于useState的setter
          const valueToStore = value instanceof Function ? value(storedValue) : value;
          
          // 保存到state
          setStoredValue(valueToStore);
          
          // 保存到localStorage
          window.localStorage.setItem(key, JSON.stringify(valueToStore));
        } catch (error) {
          console.error(`将键"${key}"保存到localStorage时出错:`, error);
        }
      };

      // 从localStorage中移除项
      const removeValue = () => {
        try {
          window.localStorage.removeItem(key);
          setStoredValue(initialValue);
        } catch (error) {
          console.error(`从localStorage移除键"${key}"时出错:`, error);
        }
      };

      // 监听其他标签页的localStorage变化
      useEffect(() => {
        const handleStorageChange = (event) => {
          if (event.key === key) {
            try {
              const newValue = event.newValue ? JSON.parse(event.newValue) : initialValue;
              setStoredValue(newValue);
            } catch (error) {
              console.error(`处理localStorage变更事件时出错:`, error);
            }
          }
        };

        // 添加事件监听器
        window.addEventListener('storage', handleStorageChange);
        
        // 清理函数
        return () => {
          window.removeEventListener('storage', handleStorageChange);
        };
      }, [key, initialValue]);

      return [storedValue, setValue, removeValue];
    };

    export default useLocalStorage;
